package com.sr.servlet.book;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sr.entity.Book;
import com.sr.service.BookService;

/**
 * Servlet implementation class BookAddServlet
 */
@WebServlet("/addBook")
public class BookAddServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BookAddServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		String bookName=request.getParameter("bookName");//这里bookName是客户端的name
		String author=request.getParameter("author");
		Book book=new Book();//实例化一个对象 
		book.setBookName(bookName);// 然后赋值  因为id自增长 因此只赋值这个
		book.setAuthor(author);
		
		if(bookName==null || bookName.equals(""))
        {//如果返回的结果是不重复的
        				System.out.println("书名不能为空！");//因此继续会到添加页面 这句值显示在控制台
        				//对request提交的内容做处理 这一操作处理完毕 分发到另一个jsp工作
        				request.getRequestDispatcher("addBook.jsp").forward(request, response);//forward()是request中的参数继续传递
        }
		else {  		
    			BookService bs=new BookService();
    			boolean result=bs.addBook(book);
    			if(result) {
        	 			System.out.println("添加成功");
        	 			request.getRequestDispatcher("findBooklist").forward(request, response);
          } else {
        	 		response.sendRedirect("addBook.jsp");	
         }
    }
	}
		

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
